<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色信息列表 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom',i1 === 0 ? 'bdtop':'', 'vcenter']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightsById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->
              <el-col :span="19">
                <!-- For 渲染二级和三级 -->
                <el-row
                  :class="[i2 === 0 ? '':'bdtop', 'vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag @close="removeRightsById(scope.row,item2.id)" closable type="success">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      @close="removeRightsById(scope.row,item3.id)"
                      closable
                      type="warning"
                      v-for="(item3,i3) in item2.children"
                      :key="item3.id"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row.children}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              @click="editRolesDialogOpen(scope.row.id)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
            >编辑</el-button>
            <!-- 删除按钮 -->
            <el-button
              @click="deleteRolesById(scope.row.id)"
              type="danger"
              icon="el-icon-delete"
              size="mini"
            >删除</el-button>
            <!-- 分配角色按钮 -->
            <el-button
              @click="rightsDialogOpen(scope.row)"
              type="warning"
              icon="el-icon-setting"
              size="mini"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框Dialog -->
    <el-dialog
      title="添加角色"
      @close="addRolesDialogClosed"
      :visible.sync="addRolesDialogVisible"
      width="50%"
    >
      <!-- 主体区域 -->
      <el-form :model="rolesForm" :rules="rolesFormRules" ref="rolesFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色信息对话框Dialog -->
    <el-dialog title="修改角色" :visible.sync="editRolesDialogVisible" width="50%">
      <!-- 主体区域 -->
      <el-form
        :model="editRolesForm"
        :rules="editRolesFormRules"
        ref="editRolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolesById">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框Dialog -->
    <el-dialog
      @close="rightsDialogClosed"
      title="分配权限"
      :visible.sync="rightsDialogVisible"
      width="50%"
    >
      <!-- 主体区域 -->
      <el-tree
        :data="rightsDataList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="rightsTreeCheckKeys"
        :props="rightsTreeDefaultProps"
        ref="rightsTreeRef"
      ></el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allowRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addRolesDialogVisible: false,
      rolesForm: {
        roleDesc: '',
        roleName: ''
      },
      editRolesForm: {},
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      editRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      editRolesDialogVisible: false,
      rightsDialogVisible: false,
      rightsDataList: [],
      rightsTreeDefaultProps: {
        children: 'children',
        label: 'authName'
      },
      rightsTreeCheckKeys: [],
      // 分配权限时 需要拿到当前角色id
      rightsTreeId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      // false
      if (res.meta.status !== 200) {
        this.$message({
          message: res.meta.msg,
          type: 'warning',
          duration: 1000
        })
        return false
      }
      // suc
      this.rolesList = res.data
    },
    removeRightsById(role, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) {
            this.$message({
              type: 'warning',
              message: res.meta.msg,
              duration: 600
            })
            return false
          }
          this.$message({
            type: 'success',
            message: '删除成功!',
            duration: 600
          })
          role.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    addRoles() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.rolesForm)
        // false
        if (res.meta.status !== 200) {
          this.$message({
            message: res.meta.msg,
            type: 'warning',
            duration: 1000
          })
          return false
        }
        // suc
        this.getRolesList()
        this.addRolesDialogVisible = false
      })
    },
    addRolesDialogClosed() {
      this.$refs.rolesFormRef.resetFields()
    },
    editRolesDialogOpen(id) {
      this.getRolesInfoById(id)
      this.editRolesDialogVisible = true
    },
    async getRolesInfoById(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      // false
      if (res.meta.status !== 200) {
        this.$message({
          message: res.meta.msg,
          type: 'warning',
          duration: 1000
        })
        return false
      }
      // suc
      this.editRolesForm = res.data
      // console.log(res)
    },
    async editRolesById() {
      const id = this.editRolesForm.roleId
      const { data: res } = await this.$http.put(
        'roles/' + id,
        this.editRolesForm
      )
      // false
      if (res.meta.status !== 200) {
        this.$message({
          message: res.meta.msg,
          type: 'warning',
          duration: 1000
        })
        return false
      }
      // suc
      this.getRolesList()
      this.editRolesDialogVisible = false
    },
    // 删除角色
    deleteRolesById(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('roles/' + id)
          // false
          if (res.meta.status !== 200) {
            this.$message({
              message: res.meta.msg,
              type: 'warning',
              duration: 1000
            })
            return false
          }
          // suc
          this.getRolesList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分配权限对话框 打开事件
    rightsDialogOpen(rightsNode) {
      this.rightsTreeId = rightsNode.id
      this.getRightsTreeList()
      this.getSubRights(rightsNode)
      this.rightsDialogVisible = true
    },
    // 获取权限信息树
    async getRightsTreeList() {
      const { data: res } = await this.$http.get('rights/tree')
      // false
      if (res.meta.status !== 200) {
        this.$message({
          message: res.meta.msg,
          type: 'warning',
          duration: 1000
        })
        return false
      }
      // suc
      // console.log(res.data);
      this.rightsDataList = res.data
    },
    // 递归 遍历角色已获得子权限
    getSubRights(rightsNode) {
      // const arr = []
      if (!rightsNode.children) {
        this.rightsTreeCheckKeys.push(rightsNode.id)
        return
      }
      rightsNode.children.forEach(i => {
        this.getSubRights(i)
      })
    },
    // 分配权限对话框 关闭事件
    rightsDialogClosed() {
      this.rightsTreeCheckKeys = []
    },
    // 确定 给角色分配权利
    async allowRights() {
      const key = [
        ...this.$refs.rightsTreeRef.getCheckedKeys(),
        ...this.$refs.rightsTreeRef.getHalfCheckedKeys()
      ]
      const keyStr = key.join(',')
      const postData = { rids: keyStr }
      const { data: res } = await this.$http.post(
        `roles/${this.rightsTreeId}/rights`,
        postData
      )
      // console.log(res)
      // false
      if (res.meta.status !== 200) {
        this.$message({
          message: res.meta.msg,
          type: 'warning',
          duration: 1000
        })
        return false
      }
      // suc
      this.$message({
        message: res.meta.msg,
        type: 'success',
        duration: 1000
      })
      this.getRolesList()
      this.rightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.vcenter {
  display: flex;
  align-items: center;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
</style>
